<template>
  <div class="message-center">
    <!-- 顶部标题栏 -->
    <el-affix :offset="0">
      <el-header class="message-header">
        <h2>消息中心</h2>
        <el-button 
          type="primary" 
          size="small" 
          plain 
          class="new-message-btn"
          @click="startNewMessage"
        >
          <el-icon><Plus /></el-icon>
          新消息
        </el-button>
      </el-header>
    </el-affix>

    <!-- 消息列表 -->
    <el-scrollbar class="message-scrollbar" @scroll="handleScroll">
      <div class="message-list">
        <div 
          v-for="message in messages" 
          :key="message.id"
          class="message-item"
          :class="{ 'unread': message.unread > 0 }"
          @click="openMessage(message)"
        >
          <!-- 头像 -->
          <el-avatar :size="48" :src="message.avatar" class="message-avatar">
            <img v-if="!message.avatar" src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
          </el-avatar>

          <!-- 消息内容 -->
          <div class="message-content">
            <div class="message-header">
              <span class="username">{{ message.username }}</span>
              <span class="time">{{ formatTime(message.time) }}</span>
            </div>
            <div class="message-preview">
              <p>{{ message.preview }}</p>
              <el-badge 
                :value="message.unread > 99 ? '99+' : message.unread" 
                :max="99"
                v-if="message.unread > 0" 
                class="unread-badge"
              />
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        <div v-if="noMore" class="no-more-messages">
          <el-divider>没有更多消息了</el-divider>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 消息数据
const messages = ref([])
const loading = ref(false)
const noMore = ref(false)
const page = ref(1)
const pageSize = ref(15)

// 加载消息
const loadMessages = async () => {
  if (loading.value || noMore.value) return
  
  loading.value = true
  try {
    const newMessages = await fetchMessages(page.value, pageSize.value)
    
    if (newMessages.length === 0) {
      noMore.value = true
      return
    }
    
    messages.value = [...messages.value, ...newMessages]
    page.value++
  } catch (error) {
    ElMessage.error('加载消息失败')
    console.error('加载消息失败:', error)
  } finally {
    loading.value = false
  }
}

// 模拟获取消息API
const fetchMessages = (page, pageSize) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const mockMessages = Array.from({ length: pageSize }, (_, i) => {
        const id = (page - 1) * pageSize + i
        return {
          id: id,
          avatar: `https://i.pravatar.cc/150?img=${Math.floor(Math.random() * 70)}`,
          username: `用户${id}`,
          preview: `这是与用户${id}的最后一条消息内容...`,
          time: Date.now() - Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000),
          unread: Math.floor(Math.random() * 10)
        }
      })

      // 模拟没有更多数据
      if (page > 3) {
        resolve([])
      } else {
        resolve(mockMessages)
      }
    }, 800)
  })
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date

  // 今天
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  }

  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天'
  }

  // 本周内
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    return weekdays[date.getDay()]
  }

  // 更早
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 打开消息
const openMessage = (message) => {
  console.log('打开消息:', message)
  // 标记为已读
  message.unread = 0
  // 实际应用中这里可以跳转到聊天页面
  // router.push(`/chat/${message.id}`)
}

// 发起新消息
const startNewMessage = () => {
  ElMessage.info('发起新消息功能')
}

// 滚动加载
const handleScroll = ({ scrollTop, clientHeight, scrollHeight }) => {
  const isNearBottom = scrollHeight - scrollTop <= clientHeight + 50
  if (isNearBottom && !loading.value && !noMore.value) {
    loadMessages()
  }
}

// 初始化加载
onMounted(() => {
  loadMessages()
})
</script>

<style scoped>
.message-center {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: var(--el-bg-color);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.message-header h2 {
  font-size: 18px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin: 0;
}

.new-message-btn {
  margin-left: auto;
}

.message-scrollbar {
  flex: 1;
}

.message-list {
  padding: 10px;
}

.message-item {
  display: flex;
  padding: 12px 15px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 8px;
}

.message-item:hover {
  background-color: var(--el-fill-color-light);
}

.message-item.unread {
  background-color: var(--el-color-primary-light-9);
}

.message-avatar {
  flex-shrink: 0;
  margin-right: 12px;
}

.message-content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.username {
  font-size: 15px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  flex-shrink: 0;
  margin-left: 10px;
}

.message-preview {
  display: flex;
  justify-content: space-between;
}

.message-preview p {
  font-size: 13px;
  color: var(--el-text-color-secondary);
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 10px;
}

.unread-badge {
  flex-shrink: 0;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  color: var(--el-text-color-secondary);
}

.loading-icon {
  margin-right: 8px;
  animation: rotating 2s linear infinite;
}

.no-more-messages {
  padding: 20px 0;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>